package com.mytools.tool.utils;


import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.widget.Toast;

import com.eboss.sbs.config.Config;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.HttpStatus;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;

//import org.apache.http.HttpEntity;
//import org.apache.http.HttpResponse;
//import org.apache.http.HttpStatus;
//import org.apache.http.client.ClientProtocolException;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.impl.client.DefaultHttpClient;

/**
 * app下载工具
 * @author Administrator
 *
 */
public class AppDownLoadUtil {
	
	public final static int TYPE_CANCEL = 0;
	public final static int TYPE_OK = 1;
	public final static int TYPE_FAIL = 2;
	
	private Context context;
	private String apkUrl;
	private boolean isForce = false;
	private AppDownLoadCallback appDownLoadCallback;
	
	public AppDownLoadUtil(Context context,String apkUrl, boolean isForce, AppDownLoadCallback appDownLoadCallback){
		this.context = context;
		this.apkUrl = apkUrl;
		this.isForce = isForce;
		this.appDownLoadCallback = appDownLoadCallback;
	}
	
	public void showUpdateNoticeDialog(String apknote){
		Builder builder = new Builder(context);
		builder.setTitle("发现新版本");
		builder.setMessage(apknote);
		builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {			
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				MyAsyncTask MyAsyncTask=new MyAsyncTask();
				MyAsyncTask.execute();
				if(appDownLoadCallback!=null)appDownLoadCallback.appDownloadFinish(TYPE_OK);
			}
		});
		builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {				
				dialog.dismiss();
				if(appDownLoadCallback!=null)appDownLoadCallback.appDownloadFinish(TYPE_CANCEL);
			}
		});
		builder.create().show();
	}
	
	/***
	 * 直接升级
	 */
	public void showUpdate(){
		MyAsyncTask MyAsyncTask=new MyAsyncTask();
		MyAsyncTask.execute();
	}

	class MyAsyncTask extends AsyncTask<Void, Integer, Boolean>{

		private ProgressDialog progressDialog;
		private String message="下载成功";
		
		@Override
		protected void onPreExecute() {
		
			if (progressDialog == null) {
				// 弹出要给ProgressDialog
		        progressDialog = new ProgressDialog(context);
		        progressDialog.setTitle("新版本更新");
		        progressDialog.setMessage("正在下载中，请稍后......");
		        //设置setCancelable(false); 表示我们不能取消这个弹出框，等下载完成之后再让弹出框消失
		        progressDialog.setCancelable(true);
		        progressDialog.setCanceledOnTouchOutside(false);
		        //设置ProgressDialog样式为圆圈的形式
		        //progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		        //设置ProgressDialog样式为水平的样式
		        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		        progressDialog.setOnDismissListener(new OnDismissListener() {
					@Override
					public void onDismiss(DialogInterface dialog) {
						cancel(true);
					}
				});
		        progressDialog.show();
			} 
			else if (!progressDialog.isShowing()) {progressDialog.show();}
			
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			
			boolean downLoadFlag=false;
			if (!isCancelled()) {

				HttpClient client = new DefaultHttpClient();    
	            HttpGet get = new HttpGet(apkUrl);    
	            try {    
	            	HttpResponse response = client.execute(get);   
	            	if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
	            		
	            		 HttpEntity entity = response.getEntity();    
	                     long length = entity.getContentLength();    
	                     InputStream is = entity.getContent();    
	                     FileOutputStream fileOutputStream = null;    
	                     if (is != null) {    
	                         File file = new File(Environment.getExternalStorageDirectory(), Config.DOWNLOAD_APK_FILENAME);
	                         fileOutputStream = new FileOutputStream(file);                           
	                         byte[] buf = new byte[1024];    
	                         int ch = -1;    
	                         int count = 0;    
	                         while ((ch = is.read(buf)) != -1) {                             
	                             fileOutputStream.write(buf, 0, ch);    
	                             count += ch;    
	                             int progress = (int)(((float)count / length) * 100);            
	                             publishProgress(progress);					
	                         }    
	                     }    
	                     fileOutputStream.flush();    
	                     if (fileOutputStream != null) {    
	                         fileOutputStream.close();    
	                     }  
	                     downLoadFlag=true;
	            	}
	            } catch (ClientProtocolException e) {                
	                e.printStackTrace();    
	            } catch (IOException e) {                  
	                e.printStackTrace();    
	            }  finally{
	            	client.getConnectionManager().shutdown();
	            }   		
			}
			return downLoadFlag;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			
            //    更新ProgressDialog的进度条
			progressDialog.setProgress(values[0]);
			
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
		
			progressDialog.dismiss();
			if(result.booleanValue()){
				message="更新成功";
				installApk();
				
			}else{
				message="更新失败";
				if(appDownLoadCallback!=null)appDownLoadCallback.appDownloadFinish(TYPE_FAIL);
			}
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
			
		}

		
	}
	
	private void installApk(){
//		Intent i = new Intent(Intent.ACTION_VIEW);
//		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		i.setDataAndType(Uri.fromFile(new File("/sdcard/"+Config.DOWNLOAD_APK_FILENAME)), "application/vnd.android.package-archive");
//		context.startActivity(i);
		File apkfile = new File("/sdcard/"+Config.DOWNLOAD_APK_FILENAME);
		if (!apkfile.exists()) {
			return;
		}

		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
			Uri apkUri = FileProvider.getUriForFile(context, "com.eboss2.sbs.fileprovider", apkfile);
			//添加这一句表示对目标应用临时授权该Uri所代表的文件
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
		} else {
			intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		}
		context.startActivity(intent);
	}
	
	public interface AppDownLoadCallback{
		public void appDownloadFinish(int index);
	}
	
}
